import { IStrategyOptions, Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UsersEntity } from '../entities/user.entity';
import { ToolsService } from '../utils/tools.service';


@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {

  @InjectRepository(UsersEntity)
  private readonly usersRepository: Repository<UsersEntity>;
  constructor( ) {
    super({
      usernameField: 'username',
      passwordField: 'password',
    } as IStrategyOptions);
  }

  async validateUser(userinfo): Promise<any> {
    const { username, password } = userinfo;
    const user = await this.usersRepository
      .createQueryBuilder('UsersEntity')
      .where('UsersEntity.username = :username', { username })
      .select(["UsersEntity"])
      .addSelect('UsersEntity.password')
      .getOne();
    if (!user) ToolsService.fail('用户名不正确');
    console.log("🚀 ~ validateUser ~ user:", user)
    //使用bcryptjs验证密码
    if (password != user.password) {
      ToolsService.fail('密码不正确');
    }
    return user;
  }

  //2.获取请求中的account和password参数进行验证。
  async validate(username: string, password: string): Promise<any> {
    const user = await this.validateUser({
      username,
      password,
    });
    console.log("🚀 ~ LocalStrategy ~ validate ~ user:", user)
    return user;
  }
}
